import React, { useState, useEffect } from 'react';
import { listSnapshots, createSnapshot, revertSnapshot, deleteSnapshot } from '../api/client';

interface Snapshot {
  name: string;
  domain: string;
  creation_time: string;
  state: string;
  description: string;
  parent: string;
  is_current: boolean;
  xml_config?: string;
}

interface SnapshotManagerProps {
  domainName: string;
  onNotification: (message: string, type: 'success' | 'error' | 'info') => void;
}

const SnapshotManager: React.FC<SnapshotManagerProps> = ({ domainName, onNotification }) => {
  const [snapshots, setSnapshots] = useState<Snapshot[]>([]);
  const [loading, setLoading] = useState(false);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showDetailsModal, setShowDetailsModal] = useState<Snapshot | null>(null);
  const [newSnapshotName, setNewSnapshotName] = useState('');
  const [newSnapshotDescription, setNewSnapshotDescription] = useState('');
  const [includeMemory, setIncludeMemory] = useState(false);
  const [diskOnly, setDiskOnly] = useState(true); // Default to disk-only for better compatibility
  const [quiesce, setQuiesce] = useState(false);
  const [atomic, setAtomic] = useState(false);

  // Load snapshots for the domain
  const loadSnapshots = async () => {
    if (!domainName) return;

    try {
      setLoading(true);
      const response = await listSnapshots(domainName);
      setSnapshots(response.data.snapshots || []);
    } catch (err: any) {
      console.error('Failed to load snapshots:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error || err.message || 'Unknown error';
      onNotification(`Failed to load snapshots: ${errorMessage}`, 'error');
    } finally {
      setLoading(false);
    }
  };

  // Create new snapshot
  const handleCreateSnapshot = async () => {
    if (!newSnapshotName.trim()) {
      onNotification('Snapshot name is required', 'error');
      return;
    }

    try {
      const snapshotConfig = {
        name: newSnapshotName.trim(),
        description: newSnapshotDescription.trim(),
        memory_state: includeMemory,
        disk_only: diskOnly,
        quiesce: quiesce,
        atomic: atomic
      };

      await createSnapshot(domainName, snapshotConfig);
      onNotification(`Snapshot "${newSnapshotName}" created successfully`, 'success');

      // Reset form and close modal
      setNewSnapshotName('');
      setNewSnapshotDescription('');
      setIncludeMemory(false);
      setDiskOnly(true);
      setQuiesce(false);
      setAtomic(false);
      setShowCreateModal(false);

      // Reload snapshots
      loadSnapshots();
    } catch (err: any) {
      console.error('Failed to create snapshot:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error || err.message || 'Unknown error';
      onNotification(`Failed to create snapshot: ${errorMessage}`, 'error');
    }
  };

  // Revert to snapshot
  const handleRevertSnapshot = async (snapshot: Snapshot) => {
    if (!confirm(`Are you sure you want to revert to snapshot "${snapshot.name}"? This will restore the VM to the state when this snapshot was taken.`)) {
      return;
    }

    try {
      await revertSnapshot(domainName, snapshot.name);
      onNotification(`Successfully reverted to snapshot "${snapshot.name}"`, 'success');
      loadSnapshots();
    } catch (err: any) {
      console.error('Failed to revert snapshot:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error || err.message || 'Unknown error';
      onNotification(`Failed to revert snapshot: ${errorMessage}`, 'error');
    }
  };

  // Delete snapshot
  const handleDeleteSnapshot = async (snapshot: Snapshot) => {
    if (!confirm(`Are you sure you want to delete snapshot "${snapshot.name}"? This action cannot be undone.`)) {
      return;
    }

    try {
      await deleteSnapshot(domainName, snapshot.name);
      onNotification(`Snapshot "${snapshot.name}" deleted successfully`, 'success');
      loadSnapshots();
    } catch (err: any) {
      console.error('Failed to delete snapshot:', err);
      const errorMessage = err.response?.data?.detail || err.response?.data?.error || err.message || 'Unknown error';
      onNotification(`Failed to delete snapshot: ${errorMessage}`, 'error');
    }
  };

  // Format date for display
  const formatDate = (dateString: string) => {
    try {
      return new Date(dateString).toLocaleString();
    } catch {
      return dateString;
    }
  };

  // Load snapshots when domain changes
  useEffect(() => {
    loadSnapshots();
  }, [domainName]);

  if (loading) {
    return (
      <div className="snapshot-manager">
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>Loading snapshots...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="snapshot-manager">
      <div className="snapshot-header">
        <h3>Snapshots ({snapshots.length})</h3>
        <button
          className="primary small"
          onClick={() => setShowCreateModal(true)}
        >
          + Create Snapshot
        </button>
      </div>

      {snapshots.length === 0 ? (
        <div className="empty-state compact">
          <div className="empty-icon">📸</div>
          <p>No snapshots available</p>
          <button
            className="primary small"
            onClick={() => setShowCreateModal(true)}
          >
            Create First Snapshot
          </button>
        </div>
      ) : (
        <div className="snapshots-list">
          {snapshots.map((snapshot) => (
            <div key={snapshot.name} className="snapshot-item">
              <div className="snapshot-info">
                <div className="snapshot-name">
                  {snapshot.name}
                  {snapshot.is_current && <span className="current-badge">Current</span>}
                </div>
                <div className="snapshot-meta">
                  <span className="snapshot-date">{formatDate(snapshot.creation_time)}</span>
                  <span className={`snapshot-state ${snapshot.state.toLowerCase().replace(' ', '-')}`}>
                    {snapshot.state}
                  </span>
                </div>
                {snapshot.description && (
                  <div className="snapshot-description">{snapshot.description}</div>
                )}
              </div>
              <div className="snapshot-actions">
                <button
                  className="action-btn small revert"
                  onClick={() => handleRevertSnapshot(snapshot)}
                  title="Revert to this snapshot"
                  disabled={snapshot.is_current}
                >
                  🔄
                </button>
                <button
                  className="action-btn small details"
                  onClick={() => setShowDetailsModal(snapshot)}
                  title="View details"
                >
                  ℹ️
                </button>
                <button
                  className="action-btn small delete"
                  onClick={() => handleDeleteSnapshot(snapshot)}
                  title="Delete snapshot"
                >
                  🗑️
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Create Snapshot Modal */}
      {showCreateModal && (
        <div className="modal-overlay" onClick={() => setShowCreateModal(false)}>
          <div className="modal-content small" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h3>Create Snapshot for {domainName}</h3>
              <button
                className="modal-close"
                onClick={() => setShowCreateModal(false)}
              >
                ✕
              </button>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label htmlFor="snapshot-name">Snapshot Name *</label>
                <input
                  id="snapshot-name"
                  type="text"
                  value={newSnapshotName}
                  onChange={(e) => setNewSnapshotName(e.target.value)}
                  placeholder="Enter snapshot name"
                  className="form-input"
                />
              </div>

              <div className="form-group">
                <label htmlFor="snapshot-description">Description</label>
                <textarea
                  id="snapshot-description"
                  value={newSnapshotDescription}
                  onChange={(e) => setNewSnapshotDescription(e.target.value)}
                  placeholder="Optional description for this snapshot"
                  className="form-textarea small"
                  rows={2}
                />
              </div>

              <div className="form-group">
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    checked={diskOnly}
                    onChange={(e) => setDiskOnly(e.target.checked)}
                  />
                  <span>Disk-only snapshot (recommended)</span>
                </label>
              </div>

              <div className="form-group">
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    checked={quiesce}
                    onChange={(e) => setQuiesce(e.target.checked)}
                  />
                  <span>Quiesce filesystem (requires guest agent)</span>
                </label>
              </div>

              <div className="form-group">
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    checked={atomic}
                    onChange={(e) => setAtomic(e.target.checked)}
                  />
                  <span>Atomic operation</span>
                </label>
              </div>
            </div>
            <div className="modal-footer">
              <button
                className="secondary small"
                onClick={() => setShowCreateModal(false)}
              >
                Cancel
              </button>
              <button
                className="primary small"
                onClick={handleCreateSnapshot}
                disabled={!newSnapshotName.trim()}
              >
                Create Snapshot
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Snapshot Details Modal */}
      {showDetailsModal && (
        <div className="modal-overlay" onClick={() => setShowDetailsModal(null)}>
          <div className="modal-content small" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h3>Snapshot Details</h3>
              <button
                className="modal-close"
                onClick={() => setShowDetailsModal(null)}
              >
                ✕
              </button>
            </div>
            <div className="modal-body">
              <div className="detail-grid compact">
                <div className="detail-item">
                  <span className="detail-label">Name:</span>
                  <span className="detail-value">{showDetailsModal.name}</span>
                </div>
                <div className="detail-item">
                  <span className="detail-label">Created:</span>
                  <span className="detail-value">{formatDate(showDetailsModal.creation_time)}</span>
                </div>
                <div className="detail-item">
                  <span className="detail-label">Status:</span>
                  <span className="detail-value">{showDetailsModal.state}</span>
                </div>
                <div className="detail-item">
                  <span className="detail-label">Current:</span>
                  <span className="detail-value">{showDetailsModal.is_current ? 'Yes' : 'No'}</span>
                </div>
                {showDetailsModal.description && (
                  <div className="detail-item full-width">
                    <span className="detail-label">Description:</span>
                    <span className="detail-value">{showDetailsModal.description}</span>
                  </div>
                )}
                {showDetailsModal.parent && (
                  <div className="detail-item">
                    <span className="detail-label">Parent:</span>
                    <span className="detail-value">{showDetailsModal.parent}</span>
                  </div>
                )}
              </div>
            </div>
            <div className="modal-footer">
              <button
                className="secondary small"
                onClick={() => setShowDetailsModal(null)}
              >
                Close
              </button>
              {!showDetailsModal.is_current && (
                <button
                  className="primary small"
                  onClick={() => {
                    handleRevertSnapshot(showDetailsModal);
                    setShowDetailsModal(null);
                  }}
                >
                  Revert to this Snapshot
                </button>
              )}
              <button
                className="danger small"
                onClick={() => {
                  handleDeleteSnapshot(showDetailsModal);
                  setShowDetailsModal(null);
                }}
              >
                Delete Snapshot
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SnapshotManager;